<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>代理模式</title>
</head>
<body>

</body>
</html>

<script>
  // 保护代理
  function sendMsg (msg) {
    console.log('msg:', msg)
  }

  function proProxy (msg) {
    if (!msg) {
      console.log('no msg:', 'no msg')
      return false
    }

    msg = '消息是：' + msg

    sendMsg(msg)
  }

  sendMsg('hha')
  proProxy()
  proProxy('hah')

  // 虚拟代理

  //图片懒加载
  const myImage = (function () {
    const imgNode = document.createElement('img')
    document.body.appendChild(imgNode)
    return {
      set: function (src) {
        imgNode.src = src
      }
    }
  })()

  const proxyImage = (function () {
    const img = new Image()
    img.onload = function () {
      setTimeout(() => {
        myImage.set(this.src)
      }, 500)
    }
    return {
      set: function (loadImg, src) {
        myImage.set(loadImg)
        img.src = src
      }
    }
  })()

  proxyImage.set('http://img.lanrentuku.com/img/allimg/1212/5-121204193Q9-50.gif', 'https://img.alicdn.com/tps/i4/TB1b_neLXXXXXcoXFXXc8PZ9XXX-130-200.png')

  // 防抖
  function debounce (fn, delay = 200) {
    let timer = null
    return function () {
      clearTimeout(timer)
      timer = null
      timer = setTimeout(() => {
        fn()
      }, delay)
    }
  }

  let count = 0
  function add () {
    console.log('count:', count++)
  }

  const proxy = (function () {
    return debounce(add)
  })()

  document.body.onmousemove = proxy
  // 缓存代理
  function addition (a, b) {
    return a + b
  }
  
  const cache = (function () {
    let hash = {}
    return {
      set: function (a, b) {
        let aa = addition(a, b)
        if (!hash[aa]) {
          return hash[aa] = aa
        }
        return hash[aa] + '缓存'
      }
    }
  })()

  console.log('cache.set(1,2):', cache.set(1,2))
  console.log('cache.set(1,2):', cache.set(1,2))
</script>